package com.bsoft.gol.hcs.common.service.impl;


import com.bsoft.gol.hcs.common.bean.request.GetMedicalRecordsReq;
import com.bsoft.gol.hcs.common.bean.response.ParameterResponse;
import com.bsoft.gol.hcs.common.dao.*;
import com.bsoft.gol.hcs.common.entity.*;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import com.bsoft.gol.hcs.common.service.IFusMedicalRecordsService;
import ctd.controller.exception.ControllerException;
import com.bsoft.gol.hcs.common.bean.request.ParamsQo;
import com.bsoft.gol.hcs.enumcase.InterfaceTypeEnum;
import com.bsoft.gol.hcs.enumcase.SysParameterEnum;
import hcn.service.commonClinical.qo.SysParameterRequest;
import com.bsoft.gol.hcs.his.bean.response.ContactsResp;
import com.bsoft.gol.hcs.his.bean.response.DiagnosisInfoResp;
import com.bsoft.gol.hcs.his.bean.response.GetMedicalRecordsResp;
import com.bsoft.gol.hcs.his.bean.response.OperativeRecordResp;
import com.bsoft.gol.hcs.his.service.OutpatientDocService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.bsoft.gol.hcs.service.rpc.IBaseParameterService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.DateUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 随访系统_就诊记录/出院记录_数据访问层接口——实现
 *
 * @author tongtp
 * @version v0.1
 * @create 2018-11-11 14:34
 **/
@Service("fusMedicalRecordsService")
public class FusMedicalRecordsServiceImpl implements IFusMedicalRecordsService {
    protected static final Logger log = LoggerFactory.getLogger(FusMedicalRecordsServiceImpl.class);

    @Autowired
    private OutpatientDocService outpatientDocService;
    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private IBaseParameterService baseParameterService;
    @Autowired
    private FusMedicalRecordsDAO fusMedicalRecordsDAO;
    @Autowired
    private FusContactsDAO fusContactsDAO;
    @Autowired
    private FusDiagnosisInfoDAO fusDiagnosisInfoDAO;
    @Autowired
    private FusOperativeRecordDAO fusOperativeRecordDAO;
    @Autowired
    private SysParameterDAO sysParameterDAO;
    /**
     * @Author:FangZhiyi
     * @Description 同步就诊记录
     * @Params  []
     * @Return  void
     * @Data Created in 2019/12/24 14:10
     * @Moddified By:
     */
    @Override
    public void synchronizationMedicalRecords() {
        String nowTime = DateUtil.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss");
        log.info(nowTime+"同步就诊记录开始！");
        ParamsQo paramsVo = new ParamsQo();
        paramsVo.setType(InterfaceTypeEnum.HOL.getCode());
        List<Map> list = baseDataService.findOrgList(paramsVo).getData();
        if (CommonUtils.isNotEmpty(list)) {
            for (Map map : list) {
                GetMedicalRecordsReq recordsReq = new GetMedicalRecordsReq();
                recordsReq.setOrganizationId(map.get("code").toString());
                recordsReq.setOrganizationName(map.get("title").toString());
                SysParameterRequest request = new SysParameterRequest();
                request.setType(InterfaceTypeEnum.HOL.getCode());
                request.setOrganizationId("0");
                List<String> strings = new ArrayList<>();
                strings.add(SysParameterEnum.MEDICAL_RECORDS_SATRT_TIME.getParameterKey());
                request.setParameterKeyList(strings);
                List<ParameterResponse> responseList = baseParameterService.getSysParameterList(request).getData();
                if (CommonUtils.isNotEmpty(responseList)) {
                    recordsReq.setLastModifyTime(responseList.get(0).getParameterValue());
                    this.getMedicalRecords(recordsReq);
                }
            }
        }

        updateSysParameterByKey(SysParameterEnum.MEDICAL_RECORDS_SATRT_TIME.getParameterKey(),
                nowTime);
        log.info(DateUtil.dateFormate(new Date(), "yyyy-MM-dd HH:mm:ss")+"同步就诊记录结束！");
    }


    public void updateSysParameterByKey(String parameterKey, String parameterValue) {
        List<SysParameter> sysParameterList = sysParameterDAO.querySysParameter(parameterKey);
        if (sysParameterList != null && sysParameterList.size() > 0) {
            SysParameter sysParameter = sysParameterList.get(0);
            sysParameter.setParameterKey(parameterKey);
            sysParameter.setParameterValue(parameterValue);
            sysParameter.setGmtModified(new Date());
            sysParameterDAO.update(sysParameter);
        }
    }

    /*同步就诊记录具体过程方法*/
    void getMedicalRecords(GetMedicalRecordsReq recordsReq) {
        log.info("开始同步医院CODE：" + recordsReq.getOrganizationId() +",时间："+recordsReq.getLastModifyTime()+ "之前的就诊记录！");
        List<GetMedicalRecordsResp> medicalRecordsRespList = null;
        try {
            medicalRecordsRespList = outpatientDocService.getMedicalRecords(recordsReq);
            if (medicalRecordsRespList != null && medicalRecordsRespList.size() > 0) {
                Date now = new Date();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (GetMedicalRecordsResp getMedicalRecordsResp : medicalRecordsRespList) {
                    FusMedicalRecords medicalRecords = new FusMedicalRecords();
                    BeanUtils.copyProperties(getMedicalRecordsResp, medicalRecords);
                    medicalRecords.setHospitalNumber(getMedicalRecordsResp.getInHospitalRecordCode());
                    medicalRecords.setPatientSex(getMedicalRecordsResp.getPatientSex());
                    medicalRecords.setPatientMobile(getMedicalRecordsResp.getPatientMobile());
                    medicalRecords.setOrganizationId(recordsReq.getOrganizationId());
                    medicalRecords.setOrganizationName(recordsReq.getOrganizationName());
                    medicalRecords.setPatientBirthday(getMedicalRecordsResp.getPatientBirthday() != null ?
                            getMedicalRecordsResp.getPatientBirthday().substring(0, 10) : "");
                    medicalRecords.setStatus(1);
                    if (StringUtils.hasText(getMedicalRecordsResp.getRecordsTime())) {
                        try {
                            medicalRecords.setRecordsTime(dateFormat.parse(getMedicalRecordsResp.getRecordsTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                            log.error("同步就诊记录日期格式化异常:{}", getMedicalRecordsResp.toString());
                        }
                    }
                    if (StringUtils.hasText(getMedicalRecordsResp.getVisitTime())) {
                        try {
                            medicalRecords.setVisitTime(dateFormat.parse(getMedicalRecordsResp.getVisitTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                            log.error("同步就诊记录日期格式化异常:{}", getMedicalRecordsResp.toString());
                        }
                    }
                    if (StringUtils.hasText(getMedicalRecordsResp.getBeAdmissionTime())) {
                        try {
                            medicalRecords.setBeAdmissionTime(dateFormat.parse(getMedicalRecordsResp.getBeAdmissionTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                            log.error("同步就诊记录日期格式化异常:{}", getMedicalRecordsResp.toString());
                        }
                    }
                    if (StringUtils.hasText(getMedicalRecordsResp.getDischargeTime())) {
                        try {
                            medicalRecords.setDischargeTime(dateFormat.parse(getMedicalRecordsResp.getDischargeTime()));
                        } catch (ParseException e) {
                            e.printStackTrace();
                            log.error("同步就诊记录日期格式化异常:{}", getMedicalRecordsResp.toString());
                        }
                    }
                    List<FusMedicalRecords> medicalRecordsList = fusMedicalRecordsDAO.queryFusMedicalRecords(
                            medicalRecords.getOrganizationId(), medicalRecords.getRecordsId(), medicalRecords.getRecordsType());
                    //已存在
                    if (CommonUtils.isNotEmpty(medicalRecordsList)) {
                        medicalRecords.setFusMedicalRecordsId(medicalRecordsList.get(0).getFusMedicalRecordsId());
                        /*删除三个子表*/
                        fusContactsDAO.deleteFusContacts(medicalRecords.getFusMedicalRecordsId());
                        fusDiagnosisInfoDAO.deleteFusDiagnosisInfo(medicalRecords.getFusMedicalRecordsId());
                        fusOperativeRecordDAO.deleteFusOperativeRecord(medicalRecords.getFusMedicalRecordsId());
                        /*更新*/
                        fusMedicalRecordsDAO.update(medicalRecords);
                    } else {
                        medicalRecords.setCreateTime(now);
                        //新增
                        fusMedicalRecordsDAO.save(medicalRecords);
                    }
                    List<ContactsResp> contactsRespList = getMedicalRecordsResp.getContactsList();
                    if (contactsRespList != null && contactsRespList.size() > 0) {
                        for (ContactsResp contactsResp : contactsRespList) {
                            FusContacts fusContacts = new FusContacts();
                            BeanUtils.copyProperties(contactsResp, fusContacts);
                            fusContacts.setFusMedicalRecordsId(medicalRecords.getFusMedicalRecordsId());
                            fusContactsDAO.save(fusContacts);
                        }
                    }
                    List<DiagnosisInfoResp> diagnosisInfoResps = getMedicalRecordsResp.getDiagnosisInfoList();
                    if (diagnosisInfoResps != null && diagnosisInfoResps.size() > 0) {
                        for (DiagnosisInfoResp diagnosisInfoResp : diagnosisInfoResps) {
                            FusDiagnosisInfo fusDiagnosisInfo = new FusDiagnosisInfo();
                            BeanUtils.copyProperties(diagnosisInfoResp, fusDiagnosisInfo);
                            fusDiagnosisInfo.setMedicalRecordsId(medicalRecords.getFusMedicalRecordsId());
                            fusDiagnosisInfo.setGmtCreate(now);
                            fusDiagnosisInfoDAO.save(fusDiagnosisInfo);
                        }
                    }
                    List<OperativeRecordResp> operativeRecordRespList = getMedicalRecordsResp.getOperativeRecordList();
                    if (operativeRecordRespList != null && operativeRecordRespList.size() > 0) {
                        for (OperativeRecordResp operativeRecordResp : operativeRecordRespList) {
                            FusOperativeRecord operativeRecord = new FusOperativeRecord();
                            BeanUtils.copyProperties(operativeRecordResp, operativeRecord);
                            operativeRecord.setMedicalRecordsId(medicalRecords.getFusMedicalRecordsId());
                            operativeRecord.setGmtCreate(now);
                            fusOperativeRecordDAO.save(operativeRecord);
                        }
                    }
                }
                //条数跟页码大小一致，说明还有下一页。
                if (medicalRecordsRespList.size() == recordsReq.getPageSize()) {
                    int pageNo = recordsReq.getPageNo();
                    recordsReq.setPageNo(pageNo + 1);
                    this.getMedicalRecords(recordsReq);
                } else {
                    log.info("结束同步医院CODE：" + recordsReq.getOrganizationId() + ",时间：" + recordsReq.getLastModifyTime() + "之前的就诊记录！");
                }
            } else {
                log.info("结束同步医院CODE：" + recordsReq.getOrganizationId() +",时间："+recordsReq.getLastModifyTime()+ "之前的就诊记录！");
            }
        } catch (ControllerException e) {
            e.printStackTrace();
        }
    }

}
